package blog.action;
import java.util.Date;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import blog.entity.Article;
import blog.entity.Comment;
import blog.enums.ArticleStatus;
import blog.service.ArticleService;
import blog.service.CommentService;
import blog.utils.CommonUtils;
import cn.hutool.http.HtmlUtil;

/**
 * @author 言曌
 * @date 2017/9/10
 */

@Controller
public class CommentAction {
    @Resource
    private CommentService commentService;

    @Resource
    private ArticleService articleService;

    /**
     * 添加评论
     */
    @RequestMapping(value = "/comment", method = {RequestMethod.POST})
    public String addComment(HttpServletRequest request, Comment comment) {
        comment.setCommentCreateTime(new Date());
        comment.setCommentIp(CommonUtils.getIpAddr(request));
        comment.setCommentAuthorAvatar(CommonUtils.getGravatar(comment.getCommentAuthorEmail()));

        //过滤字符，防止XSS攻击
        comment.setCommentContent(HtmlUtil.escape(comment.getCommentContent()));
        comment.setCommentAuthorName(HtmlUtil.escape(comment.getCommentAuthorName()));
        comment.setCommentAuthorEmail(HtmlUtil.escape(comment.getCommentAuthorEmail()));
        comment.setCommentAuthorUrl(HtmlUtil.escape(comment.getCommentAuthorUrl()));
     
        commentService.addComment(comment);
        
        //更新文章的评论数
        Article article = articleService.getArticleById(comment.getCommentArticleId());
        articleService.updateCommentCount(article.getArticleId());
        
        request.setAttribute("msg", "评论发表成功");

        return "forward:/article/"+comment.getCommentArticleId();
     
    }


}
